// 跑牌客户端的接口
import lodsah from 'lodash';

const ActionHelper = {
  // 客户端 action
  register: '注册',
  open_app: '打开app',
  play_game: '在玩游戏',
  cost_cards: '消耗房卡',
};

/**
 * 用法:
 *  1. const StatisticsHelper = require("...") // 导入本文件
 *  2. const statisticsHelper = StatisticsHelper({fetch, url, deviceInfo})
 *  3. statisticsHelper.register({userId, zipaiId})
 *
 *  说明：
 *  2. fetch 是访问 http 协议的方法;  url 是统计服务器的地址；deviceInfo 是用户设备信息
 *  3. userId 是跑牌的uid，zipaiId 是对应的 zipaiId
 *
 *  deviceInfo 的内容参考
 *  {
 *     "appId" : "com.csgame.chats",
 *     "device" : "xiaomi",
 *     "deviceId" : "19ea96dc3224e112",
 *     "mobileOS" : "Android 7.0 - msm8953 - Mozilla/5.0 (Linux; Android 7.0; Redmi Note 4X Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/64.0.3282.137 Mobile Safari/537.36",
 *     "version" : "1.0.1",
 *   }
 *
 **/
const statisticsHelper = function(options) {
  const { request, endpoint, deviceInfo } = options;
  if (!(request && endpoint && deviceInfo)) {
    console.error('初始化数据统计，参数错误', { request, endpoint, deviceInfo });
  }

  const post = function(body) {
    console.log('发送统计数据', body);
    return request(endpoint, {
      method: 'post',
      body: JSON.stringify(body),
      headers: {
        'content-type': 'application/json',
      },
    })
      .then(response => response.json())
      .catch(console.warn);
  };

  return {
    register: ({ userId, zipaiId }) => {
      const action = ActionHelper.register;
      const body = {
        action,
        userId,
        zipaiId,
        ...deviceInfo,
      };
      return post(body);
    },

    open_app: ({ userId, zipaiId }) => {
      const action = ActionHelper.open_app;
      const body = {
        action,
        userId,
        ...deviceInfo,
      };
      return post(body);
    },

    play_game: ({ userId, zipaiId }) => {
      const action = ActionHelper.play_game;
      const body = {
        action,
        userId,
        ...deviceInfo,
      };
      return post(body);
    },

    cost_cards: ({ userId, zipaiId, cost_cards, roomId }) => {
      const action = ActionHelper.cost_cards;
      const body = {
        action,
        userId,
        roomId,
        cost_cards,
        ...deviceInfo,
      };
      return post(body);
    },
  };
};

export default statisticsHelper;
